package cn.cubix.flow.controller;

import cn.cubix.flow.util.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.RuntimeServiceImpl;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.flowable.engine.runtime.ProcessInstanceQuery;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/index")
@RequiredArgsConstructor(onConstructor=@__({@Autowired,@Lazy}))
public class IndexApi {

    private final RepositoryService repositoryService;
    private final RuntimeServiceImpl runtimeService;
    private final TaskService taskService;
    private final HistoryService historyService;

    @GetMapping("/statistic/data")
    public Object statisticData(){
        Result<Object> result = Result.FAILURE().setMessage("查询失败");

        Map<String,Object> data = new HashMap<>();
        ProcessDefinitionQuery definitionQuery = repositoryService.createProcessDefinitionQuery();
        definitionQuery.latestVersion();
        data.put("definition",definitionQuery.count());

        ProcessInstanceQuery processInstanceQuery = runtimeService.createProcessInstanceQuery();
        data.put("process",processInstanceQuery.count());

        TaskQuery taskQuery = taskService.createTaskQuery();
        data.put("todoTask",taskQuery.count());

        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery();
        historicTaskInstanceQuery.finished();
        data.put("finishTask",historicTaskInstanceQuery.count());

        result.toSuccess().setMessage("查询成功").setRecord(data);
        return result;
    }


}
